//
//  HSLotteryBallDetailVC.m
//  HolyShit
//
//  Created by Robin on 2017/4/30.
//  Copyright © 2017年 HolyShit. All rights reserved.
//

#import "HSLotteryBallDetailVC.h"
#import "HSLotteryBallDetailCell.h"

@interface HSLotteryBallDetailVC ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray<HSLotteryBallDateModel *> *models;
@property (nonatomic, copy) NSString *lotId;
@property (nonatomic, strong) NSMutableArray<UIView *> *sectionViews;

@end

@implementation HSLotteryBallDetailVC

- (instancetype)initWithLotId:(NSString *)lotId lotName:(NSString *)name
{
    if (self = [super init]) {
        _lotId = lotId;
        self.title = [NSString stringWithFormat:@"%@ 开奖", name];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self commonInit];
    self.models = @[].mutableCopy;
    self.sectionViews = @[].mutableCopy;
    [self requesMatchWithIndex:0 block:nil];
}

- (void)commonInit
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 36)];
    UILabel *lb1 = [UILabel labelWithFont:MYFont(Font26) color:HEXCOLOR(HSColorBlack)];
    lb1.text = @"赛事/编号";
    lb1.textAlignment = NSTextAlignmentCenter;
    [view addSubview:lb1];
    [lb1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.bottom.mas_equalTo(0);
        make.width.mas_equalTo(ScreenWidth / 4.);
    }];
    
    UILabel *lb2 = [UILabel labelWithFont:MYFont(Font26) color:HEXCOLOR(HSColorBlack)];
    lb2.text = @"主队";
    lb2.textAlignment = NSTextAlignmentCenter;
    [view addSubview:lb2];
    [lb2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(lb1.mas_right);
        make.top.bottom.mas_equalTo(0);
        make.width.mas_equalTo(ScreenWidth / 4.);
    }];
    
    UILabel *lb3 = [UILabel labelWithFont:MYFont(Font26) color:HEXCOLOR(HSColorBlack)];
    lb3.text = @"赛果";
    lb3.textAlignment = NSTextAlignmentCenter;
    [view addSubview:lb3];
    [lb3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(lb2.mas_right);
        make.top.bottom.mas_equalTo(0);
        make.width.mas_equalTo(ScreenWidth / 4.);
    }];
    
    UILabel *lb4 = [UILabel labelWithFont:MYFont(Font26) color:HEXCOLOR(HSColorBlack)];
    lb4.text = @"客队";
    lb4.textAlignment = NSTextAlignmentCenter;
    [view addSubview:lb4];
    [lb4 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(lb3.mas_right);
        make.top.bottom.mas_equalTo(0);
        make.width.mas_equalTo(ScreenWidth / 4.);
    }];
    [self.view addSubview:view];
    [self.view addSubview:self.tableView];
}

- (void)requesMatchWithIndex:(NSUInteger)index block:(void(^)())blcok
{
    [UIWindow showProgress];
    NSDictionary *params = @{@"opencode_detail": @{@"page_index": @(index * 10),
                                                   @"lotType": self.lotId,
                                                   @"page_size": @"10"},
                             @"c_head": @{@"client_id": @"BY003000000000000002",
                                          @"client_os": @"IOS"}};
    @weakify(self);
    [[MYHttpHelper shareHelper] postWithUrl:@"http://mycp.iplay78.com/trade-web/web/opencode_detail" params:params success:^(NSDictionary *dict) {
        [UIWindow hideProgress];
        @strongify(self);
        NSDictionary *opencode_detail = dict[@"opencode_detail"];
        NSDictionary *detail = opencode_detail[@"detail"];
        if (self.models.count < 1) {
            NSArray *array = detail[@"date_list"];
            [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                HSLotteryBallDateModel *model = [HSLotteryBallDateModel new];
                model.date = obj;
                [self.models addObject:model];
            }];
        }
        
        if (self.models.count > index) {
            NSArray<HSLotteryBallDetailModel *> *detailList = [NSArray modelArrayWithClass:[HSLotteryBallDetailModel class] json:detail[@"detail_list"]];
            if (detailList.count < 1) {
                if (self.models[index].detailModels.count < 1) {
                    [self.models[index].detailModels addObject:[HSLotteryBallDetailModel new]];
                }
            }
            else{
                [self.models[index].detailModels addObjectsFromArray:detailList];
            }
        }
        if (blcok) {
            blcok();
        }
        if (index == 0 && self.models.count > 0) {
            self.models[0].isExpend = YES;
        }
        [self.tableView endRefreshAndLoadMore];
        [self.tableView reloadData];
    } failed:^(NSError *error) {
        @strongify(self);
        [self.tableView endRefreshAndLoadMore];
        [UIWindow showError:error];
    }];
}

- (void)tapView:(UIView *)view atIndex:(NSUInteger)index
{
    HSLotteryBallDateModel *model = self.models[index];
    UILabel *arrowLb = [view viewWithTag:112233+'A'];
    if (model.isExpend) {
        model.isExpend = NO;
        arrowLb.transform = CGAffineTransformMakeRotation(0);
        [self.tableView reloadSection:index withRowAnimation:UITableViewRowAnimationAutomatic];
    }
    else{
        if (model.detailModels.count < 1) {
            @weakify(self);
            [self requesMatchWithIndex:index block:^{
                @strongify(self);
                model.isExpend = YES;
                arrowLb.transform = CGAffineTransformMakeRotation(180.1 *(M_PI/180.));
                [self.tableView reloadSection:index withRowAnimation:UITableViewRowAnimationAutomatic];
            }];
        }
        else{
            model.isExpend = YES;
            arrowLb.transform = CGAffineTransformMakeRotation(180.1 *(M_PI/180.));
            [self.tableView reloadSection:index withRowAnimation:UITableViewRowAnimationAutomatic];
        }
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.models.count;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section < self.sectionViews.count) {
        return self.sectionViews[section];
    }
    
    HSLotteryBallDateModel *model = self.models[section];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 36)];
    view.backgroundColor = HEXCOLOR(HSColorBgLight);
    
    UILabel *label = [UILabel labelWithFrame:CGRectZero font:MYFont(Font24) color:HEXCOLOR(HSColorGray) text:model.date];
    label.textAlignment = NSTextAlignmentCenter;
    [view addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.mas_equalTo(0);
        make.width.mas_equalTo(ScreenWidth / 4.);
    }];
    
    UILabel *arrowLb = [UILabel labelWithFrame:CGRectZero font:IconFont(20) color:HEXCOLOR(HSColorGray) text:@""];
    if (section == 0) {
        arrowLb.transform = CGAffineTransformMakeRotation(180.1 *(M_PI/180.));
    }
    arrowLb.tag = 112233 + 'A';
    [view addSubview:arrowLb];
    [arrowLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-15);
        make.centerY.equalTo(label);
    }];
    
    @weakify(self, view);
    [view bk_whenTapped:^{
        @strongify(self, view);
        [self tapView:view atIndex:section];
    }];
    
    [view showLineForHorizontal];
    MYLine *lineTop = [view lineWithDirection:MYDirectionTop];
    [lineTop manualSetBgColor:HEXCOLOR(HSColorRed)];
    MYLine *lineBottom = [view lineWithDirection:MYDirectionBottom];
    [lineBottom manualSetBgColor:HEXCOLOR(HSColorRed)];
    
    [self.sectionViews addObject:view];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 36;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    HSLotteryBallDateModel *model = self.models[section];
    return model.isExpend ? model.detailModels.count : 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 56;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HSLotteryBallDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([HSLotteryBallDetailCell class])];
    [cell updateModel:self.models[indexPath.section].detailModels[indexPath.row] atIndex:indexPath.row];
    return cell;
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 36, self.view.width, self.view.height - NavBarHeight - 36)];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        @weakify(self);
        [_tableView addRefreshBlock:^{
            @strongify(self);
            [self requesMatchWithIndex:0 block:nil];
        }];
        [_tableView registerClass:[HSLotteryBallDetailCell class] forCellReuseIdentifier:NSStringFromClass([HSLotteryBallDetailCell class])];
    }
    return _tableView;
}

@end
